package com.njd.test.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.njd.test.config.JfinalConfig;
import com.njd.test.entity.Data;
import com.njd.test.entity.Module;
import com.njd.test.entity.Project;

/**
 * 压力测试 结果 图表
 * 
 * @author Johnson Zhang
 *
 */
public class PressureController extends Controller {

	public void index() {
		setAttr("active", 1);
		setAttr("basePath", JfinalConfig.BASE_PATH);
		
		setAttr("projectList", Project.dao.getProjectList());
	}

	public void show() {
		String dates = getPara("dates", "");
		int projectId = getParaToInt("projectId", 0);

		setAttr("active", 2);
		setAttr("dates", dates);
		setAttr("projectId", projectId);
		if (StrKit.isBlank(dates)) {
			setAttr("datesList", new ArrayList<String>());
		} else {
			setAttr("datesList", Arrays.asList(dates.split(",")));
		}

		setAttr("projectList", Project.dao.getProjectList());
		setAttr("basePath", JfinalConfig.BASE_PATH);
	}

	

	public void showAjaxData() throws ParseException {
		String dates = getPara("dates", "");
		int projectId = getParaToInt("projectId", 0);
		String type = getPara("type", "TPS");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		if (projectId <= 0) {
			renderErrorJson("参数错误");
			return;
		}

		List<String> datesList = new ArrayList<String>();
		if (StrKit.isBlank(dates)) {
			Date now = new Date();

			String queryDate = df.format(now);

			datesList = Data.dao.getNearDate(queryDate, projectId);

		} else {
			String[] datesSplit = dates.split(",");
			datesList = Arrays.asList(datesSplit);

			List<Date> datesSortList = new ArrayList<Date>();
			for (String s : datesList) {
				datesSortList.add(df.parse(s));
			}

			Collections.sort(datesSortList, new Comparator<Date>() {
				public int compare(Date arg0, Date arg1) {
					return arg0.compareTo(arg1);
				}
			});

			datesList = new ArrayList<String>();
			for (Date d : datesSortList) {
				datesList.add(df.format(d));
			}
		}

		Map<String, Object> result = new HashMap<String, Object>();
		List<String> listLegend = new ArrayList<String>();
		List<Map<String, Object>> seriesMapList = new ArrayList<Map<String, Object>>();

		List<Data> dataList = Data.dao.getListByDate(datesList, projectId);

		for (Data d : dataList) {
			String legendStr = d.getProjectname() + "," + d.getModulename()
					+ ",并发" + d.getConcurrentuser();

			if (listLegend.contains(legendStr)) {
				continue;
			}

			listLegend.add(legendStr);
		}

		for (String s : listLegend) {
			Map<String, Object> mapSeries = new HashMap<String, Object>();

			mapSeries.put("name", s);
			mapSeries.put("type", "line");
			mapSeries.put("showAllSymbol", true);
			List<String> seriesData = new ArrayList<String>();
			for (String ds : datesList) {
				boolean isHave = false;
				for (Data d : dataList) {
					String legendStr = d.getProjectname() + ","
							+ d.getModulename() + ",并发" + d.getConcurrentuser();

					if (legendStr.equals(s)
							&& df.format(d.getDate()).equalsIgnoreCase(ds)) {
						// switch (type.toLowerCase()) {
						// case "responsetime":
						// seriesData.add(d.getResponsetime());
						// break;
						// default:
						// seriesData.add(d.getTps());
						// break;
						// }
						if (type.equalsIgnoreCase("responsetime")) {
							seriesData.add(d.getResponsetime());
						} else {
							seriesData.add(d.getTps());
						}
						isHave = true;
					}
				}

				if (!isHave) {
					seriesData.add("0");
				}
			}

			mapSeries.put("data", seriesData);

			seriesMapList.add(mapSeries);
		}

		result.put("series", seriesMapList);
		result.put("legend", listLegend);
		result.put("xAxisData", datesList);
		if (type.equalsIgnoreCase("TPS")) {
			result.put("dataList", dataList);
		}

		renderSuccessJson("success", result);
	}

	@SuppressWarnings("unchecked")
	public void save() throws ParseException {
		String dataJson = getPara("json");
		String date = getPara("date");

		if (StrKit.isBlank(date) || StrKit.isBlank(dataJson)) {
			renderErrorJson("错误的参数");
			return;
		}

		List<Map<String, String>> mapList = com.alibaba.fastjson.JSON
				.parseObject(dataJson, List.class);

		for (Map<String, String> map : mapList) {
			String id = map.get("dataId");
			String projectName = map.get("projectName");
			String moduleName = map.get("moduleName");
			String concurrentUser = map.get("concurrentUser");
			String tps = map.get("tps");
			String responseTime = map.get("responseTime");
			String successRate = map.get("successRate");
			String successReponse = map.get("successReponse");
			String errorReponse = map.get("errorReponse");
			String remark = map.get("remark");
			String projectId = map.get("projectId");
			String moduleId = map.get("moduleId");
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

			if (StrKit.isBlank(id) || id.equals("0")) {
				new Data(0, Integer.valueOf(moduleId), remark, moduleName,
						concurrentUser, Integer.valueOf(projectId),
						errorReponse, successReponse, df.parse(date),
						projectName, successRate, responseTime, tps).save();
			} else {
				Data data = Data.dao.findById(id);
				data.setData(Integer.valueOf(id), Integer.valueOf(moduleId),
						remark, moduleName, concurrentUser,
						Integer.valueOf(projectId), errorReponse,
						successReponse, df.parse(date), projectName,
						successRate, responseTime, tps).update();
			}
		}

		renderSuccessJson("success", null);
	}

	public void dataList() {
		String date = getPara("date");
		int projectId = getParaToInt("projectId", 0);

		if (StrKit.isBlank(date)) {
			renderJson();
		} else {
			renderJson(Data.dao.list(date, projectId));
		}
	}

//	public void echart() {
//		String date = getPara("date");
//
//		List<Data> dataList = Data.dao.list(date);
//
//		Map<String, Object> result = new HashMap<String, Object>();
//
//		List<String> listProject = new ArrayList<String>();
//		List<Map<String, Object>> seriesMapList = new ArrayList<Map<String, Object>>();
//		for (Data data : dataList) {
//			String projectName = data.getId() + ":" + data.getProjectname()
//					+ "(" + data.getModulename() + ")";
//			listProject.add(projectName);
//		}
//
//		List<String> legend = new ArrayList<String>();
//		legend.add("TPS");
//		legend.add("响应时间");
//		legend.add("成功率");
//
//		for (String s : legend) {
//			Map<String, Object> map = new HashMap<String, Object>();
//			map.put("name", s);
//			map.put("type", "bar");
//			List<String> valueList = new ArrayList<String>();
//			for (Data data : dataList) {
//				if (s.equalsIgnoreCase("tps")) {
//					valueList.add(data.getTps());
//				} else if (s.equalsIgnoreCase("响应时间")) {
//					valueList.add(data.getSuccessreponse());
//				} else if (s.equalsIgnoreCase("成功率")) {
//					valueList.add(data.getSuccessrate());
//				}
//			}
//
//			map.put("data", valueList);
//
//			seriesMapList.add(map);
//		}
//
//		result.put("projectName", listProject);
//		result.put("series", seriesMapList);
//		result.put("legend", legend);
//
//		renderSuccessJson("success", result);
//	}

	public void delete() {
		int dataId = getParaToInt("dataId", 0);

		if (dataId > 0) {
			Data.dao.deleteById(dataId);

			renderSuccessJson("success", null);
		} else {
			renderErrorJson("error");
		}
	}
	
	
	public void project() {
		int projectId = getParaToInt("projectId", 0);
		List<Project> projectList = Project.dao.getProjectAndModuleList(projectId);
		
		setAttr("projectSelectList", Project.dao.getProjectList());
		
		setAttr("projectList", projectList);
		setAttr("projectId", projectId);
		setAttr("active", 1);
		setAttr("basePath", JfinalConfig.BASE_PATH);
	}
	
	public void saveProject() {
		int id = getParaToInt("id", 0);
		String name = getPara("name");
		int projectId = getParaToInt("projectId", 0);
		
		if (StrKit.notBlank(name)) {
			if (id <= 0) {
				if (projectId > 0) {
					//新增模块名称 
					new Module(0, 0, projectId, name).save();
				} else {
					//新增项目名称
					
					new Project(0, name, 0).save();
				}
			} else {
				//更新
				if (projectId > 0) {
					//更新模块名称 
					new Module(id, 0, projectId, name).update();
					
					Data.dao.updateModuleOrProjectName(name, id, "module");
				} else {
					//更新项目名称 
					new Project(id, name, 0).update();
					
					Data.dao.updateModuleOrProjectName(name, id, "project");
				}
			}
			
			renderSuccessJson("success", null);
		} else {
			renderErrorJson("参数错误");
		}
	}
	
	public void getModuleList() {
		renderJson(Module.dao.getModuleList());
	}
	


	private void renderErrorJson(String message) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		result.put("message", message);
		result.put("data", null);
		result.put("status", 404);

		renderJson(result);
	}

	private void renderSuccessJson(String message, Object obj) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		result.put("message", message);
		result.put("data", obj);
		result.put("status", 200);

		renderJson(result);
	}

}
